/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package cmd

import (
	"os"

	"github.com/spf13/cobra"

	"gitee.com/banggua/ggtsync/logger"
	"gitee.com/banggua/ggtsync/logger/zap"
)

var (
	versionFlag bool
	testFlag    bool
	zapFlag     bool
	signalFlag  string
	configFlag  string
)

func init() {
	rootCmd.PersistentFlags().BoolVarP(&versionFlag, "version", "v", false, "show version and exit")
	rootCmd.PersistentFlags().BoolVarP(&testFlag, "test", "t", false, "test configuration and exit")
	rootCmd.PersistentFlags().BoolVarP(&zapFlag, "zap", "z", false, "use zap logger")
	rootCmd.PersistentFlags().StringVarP(&signalFlag, "signal", "s", "start", "send signal to a master process: start, quit, reload")
	rootCmd.PersistentFlags().StringVarP(&configFlag, "config", "c", "ggtsync.yaml", "config file")
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "ggtsync",
	Short: " An extensible synchronization tool",
	Run: func(cmd *cobra.Command, args []string) {
		if zapFlag {
			logger.SetLogger(zap.ZapLogger)
		}

		if versionFlag {
			Version()
		}

		if testFlag {
			Test(configFlag)
		}

		Signal(signalFlag, configFlag)
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		logger.Errorf("%v", err)
		os.Exit(1)
	}
}
